package bojan.robots.market;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import sim.util.Double2D;
import bojan.robots.motion.Navigation;

public class Market {

	private List<Navigation> agents;

	public Market(List<Navigation> agents) {
		super();
		this.agents = agents;
	}

	public Navigation offer(List<Navigation> bidders, Double2D goal, double price ) {
		
		Navigation winner = null;
		for (Navigation bidder : bidders) {
			if (bidder .offer(goal) > price) {
				winner  = bidder;
				price = bidder .value(goal);
			}
		}
		return winner;
	}
	
	public boolean sell(Navigation auctioneer, Double2D double2d, double price) {

		List<Navigation> bidders = bidders(auctioneer);
		Navigation buyer = offer(bidders, double2d, price);
		if (buyer != null) {
			auctioneer.sold(double2d);
			buyer.bought(double2d);
		}
		return false;
	}

	public List<Navigation> bidders(Navigation auctioneer) {
		List<Navigation> bidders = new ArrayList<Navigation>(agents.size());
		for (Navigation navigation : agents) {
			bidders.add(navigation);
		}		
		bidders.remove(auctioneer);
		return bidders;
	}

}
